package com.qdlc.p2p.biz.tpp.model;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.log4j.Logger;

import com.qdlc.p2p.common.constant.SinaConstant;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.NumberUtil;
import com.qdlc.p2p.common.util.SinaBase64;
import com.qdlc.p2p.common.util.SinaRSA;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dao.TppMemberAgentDao;
import com.qdlc.p2p.dal.dto.MemberAgent;
import com.qdlc.p2p.dal.dto.TppSinaSplit;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 
 *  新浪支付 help
 * @author ygw
 * @version 2.0
 * @date 2015年8月10日 下午2:56:08
 */
public class SinaHelper {
	
	private static final Logger logger = Logger.getLogger(SinaHelper.class);
	
	private static SinaModel doSubmit(SinaModel model) {
		try {
			model.submit();
		} catch (Exception e) {
			model = null;
			logger.error(e.getMessage());
			logger.error(e.getStackTrace());
		}
		return model;
	}
	
	
	/**
	 *  新浪开户
	 * @param model：唯一标识
	 * @return
	 */
	public static SinaModel tppRegister(TppModel model){
		UserCache userCache = UserUtils.getUserCacheByUserId(model.getUser());
		SinaRegister register = new SinaRegister(userCache.getUserNature()+"", "", model.getUuid());
		return  doSubmit(register);
	}
	
	/**
	 *  新浪实名
	 * @param model 实名用户
	 * @return
	 */
	public static SinaModel tppRealName(TppModel model) {
		User user = model.getUser();
		String encrypt = SystemConfigHelper.getValue(Nid.CON_ENCRYPT);
		byte[] real_name_byte = null;
		byte[] cert_no_byte = null;
		try {
			real_name_byte = SinaRSA.encryptByPublicKey(user.getRealName().getBytes("utf-8"), encrypt);
			cert_no_byte = SinaRSA.encryptByPublicKey(user.getCardId().getBytes("utf-8"), encrypt);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String base64_real_name_encrypt = SinaBase64.encode(real_name_byte);
		String base64_cert_no_encrypt = SinaBase64.encode(cert_no_byte);
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		SinaRealName realName = new SinaRealName(base64_real_name_encrypt, base64_cert_no_encrypt, "", tppUserCustId);
		return doSubmit(realName);
	}
	
	/**
	 *  新浪绑定认证信息
	 * @param userIdentify 
	 * @param model 用户
	 * @return
	 */
	public static SinaModel bindingVerify(TppModel model, UserIdentify userIdentify) {
		User user = model.getUser();
		String encrypt = SystemConfigHelper.getValue(Nid.CON_ENCRYPT);
		byte[] TppMobilePhone = null;
		try {
			String tppMobilePhone = UserUtils.getUserTppMobilePhone(user.getUserId());
			TppMobilePhone = SinaRSA.encryptByPublicKey(tppMobilePhone.getBytes(), encrypt);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String base64_TppMobilePhone = SinaBase64.encode(TppMobilePhone);
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		SinaBindingVerify bv = new SinaBindingVerify(userIdentify.getTppVerifyType(), base64_TppMobilePhone, "", tppUserCustId);
		return doSubmit(bv);
	}
	
	

	/**
	 * 新浪充值
	 *  方法说明
	 * @param model
	 * @return
	 * @param
	 * @throws Exception 
	 */
	public static SinaRecharge tppRecharge(TppModel model) {
		UserCache userCache = UserUtils.getUserCacheByUserId(model.getUser().getUserId());
		SinaRecharge recharge = new SinaRecharge(model.getTppUserCustId(),model.getMoney()+"",model.getBank_code(), userCache.getUserNature());
		String sign = "";
		try {
			String signTem = recharge.sign(recharge.getSignParamNames());
			sign = URLEncoder.encode(signTem, "UTF-8");
			recharge.setSign(sign);
			recharge.setSignStr(sign);
		} catch (Exception e) {
			logger.error("充值签名失败..");
			e.printStackTrace();
		}
		return recharge;
	}
	
	/**
	 * 查询用户第三方余额
	 * @param model
	 * @return
	 */
	public static SinaModel tppQueryBalance(TppModel model) {
		String tppUserCustId = UserUtils.getUserTppCustId(model.getUser().getUserId());
		SinaQueryBalance queryBalance = new SinaQueryBalance(SystemConfigHelper.getValue(Nid.ACCOUNT_TYPE), tppUserCustId);
		return doSubmit(queryBalance);
	}

	/**
	 * 查询平台第三方余额
	 * @return
	 */
	public static SinaModel tppQueryWebBalance() {
		SinaQueryWebBalance queryBalance = new SinaQueryWebBalance(SystemConfigHelper.getValue(Nid.ACCOUNT_TYPE), SystemConfigHelper.getValue(Nid.MERCHANT_ID));
		return doSubmit(queryBalance);
	}
	
	/**
	 * 查询新浪收支明细
	 * @param model
	 * @return
	 */
	public static SinaModel tppQueryAccountDetails(TppModel model) {
		String tppUserCustId = UserUtils.getUserTppCustId(model.getUser().getUserId());
		SinaQueryAccountDetails qad = new SinaQueryAccountDetails(SystemConfigHelper.getValue(Nid.ACCOUNT_TYPE), tppUserCustId, model.getStartTime(), model.getEndTime(), model.getExtendParam());
		return doSubmit(qad);
	}
	
	/**
	 * 查询新浪收支明细以及分页信息
	 * @param model
	 * @return
	 */
	public static SinaModel tppQueryAccountDetailsPagination(TppModel model) {
		String page = String.valueOf(model.getPage());
		String rows = String.valueOf(model.getRows());
		String tppUserCustId = UserUtils.getUserTppCustId(model.getUser().getUserId());
		SinaQueryAccountDetails qad = new SinaQueryAccountDetails(SystemConfigHelper.getValue(Nid.ACCOUNT_TYPE),tppUserCustId, model.getStartTime(), model.getEndTime(),page,rows, model.getExtendParam());
		return doSubmit(qad);
	}
	
	/**
	 * 查询存钱罐基金收益率
	 * @param model
	 * @return
	 */
	public static SinaModel tppQueryFundYield(TppModel model) {
		SinaQueryFundYield queryFundYield = new SinaQueryFundYield(SystemConfigHelper.getValue(Nid.FUND_CODE));
		return doSubmit(queryFundYield);
	}
	
	/**
	 * 
	 *  冻结
	 * @param model
	 * @return
	 * @param
	 */
	public static SinaModel tppFreeze(TppModel model){
		SinaBalanceFreeze freeze = new SinaBalanceFreeze(model.getTppUserCustId(), model.getMoney()+"", model.getSummary(),model.getExtendParam());
		return doSubmit(freeze);
	}
	
	/**
	 * 
	 *  解冻
	 * @param model
	 * @return
	 * @param
	 */
	public static SinaModel tppUnFreeze(TppModel model){
		SinaBalanceUnFreeze freeze = new SinaBalanceUnFreeze(model.getTppUserCustId(), model.getOrderId(), model.getMoney()+"", model.getSummary(),model.getExtendParam());
		return doSubmit(freeze);
	}
	
	/**
	 * 新浪代收接口
	 *  方法说明
	 * @return
	 * @param
	 */
	public static SinaModel tppCollectTrade(TppModel model){
		logger.info("代收订单号："+model.getOrderId());
		SinaCollectTrade collTrade = new SinaCollectTrade(model.getTppUserCustId(), model.getIdentityType(), model.getOut_trade_code(), 
				model.getSummary(),model.getTppBorrowId(), model.getCan_repay_on_failed(), "", model.getMoney()+"",model.getOrderId());
		return doSubmit(collTrade);
	}
	
	/**
	 * 新浪取现
	 * @param model
	 * @return
	 */
	public static SinaModel tppCash(TppModel model) {
		String tppUserCustId = UserUtils.getUserTppCustId(model.getUser().getUserId());
		SinaWithdraw withdraw = new SinaWithdraw(model.getOrderId(), SystemConfigHelper.getValue(Nid.ACCOUNT_TYPE), 
				NumberUtil.format2Str(model.getMoney()), NumberUtil.format2Str(model.getServFee()), tppUserCustId, model.getBank_card_id());
		return doSubmit(withdraw);
	}
	
	/**
	 * <p>新浪代付接口</p>
	 * @author 原系统 2016年2月14日 上午10:55:27
	 * @param model
	 * @return
	 * @modificationHistory=========================逻辑或功能性重大变更记录
	 * @modify by user: Kaiju Zhao 2016年2月14日 上午10:55:27
	 * @modify by reason: 规范代码
	 */
    public static SinaModel tppPayTrade(TppModel model) {
        String tppType = model.getTppType();
        String payeeIdentityId = model.getTppUserCustId();
        String outTradeCode = model.getOut_trade_code();
        String amount = model.getMoney() + "";
        String summary = model.getSummary();
        String goodsId = model.getTppBorrowId();
        String outTradeNo = model.getOrderId();
        List<TppSinaSplit> splitList = model.getSplit_list();

        if (TppModel.TPP_REPAY.equals(tppType) 
                || TppModel.TPP_LOAN.equals(tppType)
                || SinaConstant.TRADE_SERVICE_RED_ENVELOPE_EXCHAGE.equals(tppType)) { 
            // 放款、还款、红包兑换取收款人标识为ToTppUserCustId
            payeeIdentityId = model.getToTppUserCustId();
        }
        SinaPayTrade payTrade = new SinaPayTrade(payeeIdentityId, outTradeCode, amount, 
                summary, goodsId, outTradeNo, splitList);
        return doSubmit(payTrade);
    }
	
	/** 
	 * 	新浪 - 绑定银行卡接口
	 * @param model
	 * @return
	 */
	
	public static SinaModel tppBindBankCard(TppModel model){
		User user = model.getUser();
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		SinaBindBankCard bindCard = new SinaBindBankCard(model.getBank_code(),model.getBankCardId(),"","",model.getCard_attribute(),"","","","",model.getProvince(),model.getCity(),"","","",tppUserCustId);
		return doSubmit(bindCard);
	}
	

	/**
	 * 新浪 - 解绑银行卡接口
	 * @param model
	 * @return
	 */
	public static SinaModel tppUnBindBankCard(TppModel model){
		User user = model.getUser();
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		SinaUnBindBankCard unBindCard = new SinaUnBindBankCard(model.getBank_card_id(),"",tppUserCustId);
		return doSubmit(unBindCard);
	}
	
	/**
	 * 新浪 - 查询银行卡接口
	 * @param model
	 * @return
	 */
	public static SinaModel tppQueryBankCard(TppModel model) {
		User user = model.getUser();
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		SinaQueryBankCard queryBankCard = new SinaQueryBankCard("","",tppUserCustId);
		return doSubmit(queryBankCard);
	}
	
	/**
	 * 新浪 - 托管退款接口
	 * @param model
	 * @return
	 */
	public static SinaModel tppRefund(TppModel model){
		SinaRefund refund = new SinaRefund(model.getOrderId(),model.getSubOrdId(), model.getMoney()+"",
				model.getServiceTypeStr(),"",model.getExtendParam());
		return doSubmit(refund);
	}
	
	/**
	 * 新浪 - 经办人信息
	 * @param model
	 * @return
	 */
	public static SinaModel tppMemberAgent(TppModel model) {
		User user = model.getUser();
		String encrypt = SystemConfigHelper.getValue(Nid.CON_ENCRYPT);
		byte[] agent_name_byte = null;
		byte[] license_no_byte = null;
		byte[] agent_mobile_byte = null;
		try {
			TppMemberAgentDao tppMemberAgentDao = (TppMemberAgentDao) BeanUtil.getBean("tppMemberAgentDao");
			MemberAgent memberAgent = tppMemberAgentDao.findMemberAgentByUserId(user.getUserId());
			agent_name_byte = SinaRSA.encryptByPublicKey(memberAgent.getAgent_name().getBytes("utf-8"), encrypt);
			license_no_byte = SinaRSA.encryptByPublicKey(memberAgent.getLicense_no().getBytes("utf-8"), encrypt);
			agent_mobile_byte = SinaRSA.encryptByPublicKey(memberAgent.getAgent_mobile().getBytes("utf-8"), encrypt);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String base64_agent_name_byte_encrypt = SinaBase64.encode(agent_name_byte);
		String base64_license_no_byte_encrypt = SinaBase64.encode(license_no_byte);
		String base64_agent_mobile_byte_encrypt = SinaBase64.encode(agent_mobile_byte);
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		SinaMemberAgent memberAgent = new SinaMemberAgent(base64_agent_name_byte_encrypt, base64_license_no_byte_encrypt,base64_agent_mobile_byte_encrypt, "", tppUserCustId);
		return doSubmit(memberAgent);
	}
}
